package com.gg.registration.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gg.common.helper.HttpRequestHelper;
import com.gg.common.result.ResultCodeEnum;
import com.gg.common.utils.MD5;
import com.gg.common.utils.RegistrationException;
import com.gg.registration.enums.OrderStatusEnum;
import com.gg.registration.model.order.OrderInfo;
import com.gg.registration.model.user.Patient;
import com.gg.registration.order.feignClient.HospitalFeignClient;
import com.gg.registration.order.feignClient.PatientFeignClient;
import com.gg.registration.order.mapper.OrderMapper;
import com.gg.registration.order.service.OrderService;
import com.gg.registration.order.service.WechatPayService;
import com.gg.registration.rabbitmq.constant.MQConstant;
import com.gg.registration.rabbitmq.service.RabbitService;
import com.gg.registration.vo.hosp.ScheduleOrderVo;
import com.gg.registration.vo.msm.MsmVo;
import com.gg.registration.vo.order.*;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * Author：  chenjunjia
 * Date：    2022/4/23 18:04
 * WeChat：  China_JoJo_
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Resource
    private HospitalFeignClient hospitalFeignClient;

    @Resource
    private PatientFeignClient patientFeignClient;

    @Resource
    private RabbitService rabbitService;

    @Resource
    private WechatPayService wechatPayService;

    /**
     * 保存订单
     * 根据科室编号、就诊人编号进行保存
     * 【未解决】rabbitmq发送的反序列化问题
     * @param scheduleId 科室编号
     * @param patientId  就诊人编号
     * @return 返回订单 id 号
     */
    @Transactional
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //获取就诊人信息
        Patient patient = patientFeignClient.getPatient(patientId);
        if (null == patient) {
            throw new RegistrationException(ResultCodeEnum.PARAM_ERROR);
        }
        // 获取排班详细信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        if (null == scheduleOrderVo) {
            throw new RegistrationException(ResultCodeEnum.PARAM_ERROR);
        }
        // 当前时间不可以预约
        // 早于scheduleOrderVo的startTime || 晚于scheduleOrderVo的endTime
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new RegistrationException(ResultCodeEnum.TIME_NO);
        }
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        if (null == scheduleOrderVo) {
            throw new RegistrationException(ResultCodeEnum.PARAM_ERROR);
        }
        if (scheduleOrderVo.getAvailableNumber() <= 0) {
            throw new RegistrationException(ResultCodeEnum.NUMBER_NO);
        }
        // 将上述获取到的就诊人信息、排班详细信息设置到订单中
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        // 保存订单
        this.save(orderInfo);

        // 将参数设置进map中
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        // 联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
//        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        String sign = MD5.encrypt(signInfoVo.getSignKey());
        paramMap.put("sign", sign);

        // 利用 HttpRequestHelper 向医院方的接口发起请求，然后医院方返回一个map，里面包含了订单信息
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");

        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            // 预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            // 预约序号
            Integer number = jsonObject.getInteger("number");
            // 取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            // 取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            // 更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            // 排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            // 排班剩余预约数（减号数的操作在医院方完成，本挂号系统不操作，只拿返回数据）
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            // TODO 发送mq信息更新号源和短信通知
            // 发送mq信息更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            // 短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
//            msmVo.setTemplateCode("SMS_194640721");
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);

            orderMqVo.setMsmVo(msmVo);
            //发去给医院模块的 HospitalListener
            rabbitService.sendMessage(MQConstant.EXCHANGE_DIRECT_ORDER, MQConstant.ROUTING_ORDER, orderMqVo);
        } else {
            throw new RegistrationException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }

        return orderInfo.getId();
    }

    /**
     * 查询订单
     *
     * @param orderId 订单id
     * @return
     */
    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        return packOrderInfo(orderInfo);
    }

    /**
     * 订单列表（条件查询带分页）
     * @param pageParam
     * @param orderQueryVo
     * @return
     */
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人id
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        //设置条件
        wrapper.like(null != name, "hosname", name);
        wrapper.eq(null != patientId, "patient_id", patientId);
        wrapper.eq(null != orderStatus, "order_status", orderStatus);
        wrapper.ge(null != reserveDate, "reserve_date", reserveDate);
        wrapper.ge(null != createTimeBegin, "create_time", createTimeBegin);
        wrapper.le(null != createTimeEnd, "create_time", createTimeEnd);
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packOrderInfo(item);
        });
        return pages;
    }

    /**
     * 取消订单
     * @param orderId
     */
    @Transactional
    @Override
    public Boolean cancelOrder(Long orderId) throws Exception {
        //先获取订单
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        /**
         * 测试要退款但超时了，可以注释掉这个判断（滑稽.jpg）
         */
        //判断时间是否满足可以取消预约的条件
        DateTime quitTime = new DateTime(orderInfo.getQuitTime());
        if (quitTime.isBeforeNow()) {//截止时间在现在之前，说明已经超时，不可取消预约
            throw new RegistrationException(ResultCodeEnum.CANCEL_ORDER_NO);
        }
        //调用医院接口进行取消预约操作
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (null==signInfoVo) {
            throw new RegistrationException(ResultCodeEnum.PARAM_ERROR);
        }
        //封装向医院请求所需的参数
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("hoscode",orderInfo.getHoscode());//看了下医院方接口，这两个参数用不着
        reqMap.put("hosRecordId",orderInfo.getHosRecordId());
        reqMap.put("timestamp", HttpRequestHelper.getTimestamp());//用不着，但还是写上吧
        String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
        reqMap.put("sign", sign);//用不着，但还是写上吧
        //发送请求 【服务调用，以后用feign】
        JSONObject result = HttpRequestHelper.sendRequest(reqMap, signInfoVo.getApiUrl()+"/order/updateCancelStatus");

        //接收医院返回的数据，并判断订单是否可以取消
        if(result.getInteger("code")!=200) {
            throw new RegistrationException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        } else {
            //判断是否可以取消，已支付状态才可以取消
            if (OrderStatusEnum.PAID.getStatus().intValue() == orderInfo.getOrderStatus().intValue()) {
                //微信退款
                Boolean isRefund = wechatPayService.refund(orderId);
                if (!isRefund) {
                    throw new RegistrationException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                }
                //修改订单状态
                orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
                baseMapper.updateById(orderInfo);
                //发送mq更新预约数量
                OrderMqVo orderMqVo = new OrderMqVo();
                orderMqVo.setScheduleId(orderInfo.getScheduleId());
                //短信提示
                MsmVo msmVo = new MsmVo();
                msmVo.setPhone(orderInfo.getPatientPhone());
                String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
                Map<String,Object> param = new HashMap<String,Object>(){{
                    put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                    put("reserveDate", reserveDate);
                    put("name", orderInfo.getPatientName());
                }};
                msmVo.setParam(param);
                orderMqVo.setMsmVo(msmVo);
                rabbitService.sendMessage(MQConstant.EXCHANGE_DIRECT_ORDER, MQConstant.ROUTING_ORDER, orderMqVo);
            }
        }
        return null;
    }

    /**
     * 自动发送短信，提醒就诊人就诊
     */
    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        //筛选出当天符合日期的就诊人
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        //遍历出每个就诊人，然后提醒
        for(OrderInfo orderInfo : orderInfoList) {
            //短信提示
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("phone",orderInfo.getPatientPhone());
            }};
            //SMS那边是接收一个Map，注意一下就行了
            rabbitService.sendMessage(MQConstant.EXCHANGE_DIRECT_MSM, MQConstant.ROUTING_MSM_ITEM, param);
        }
    }

    /**
     * 订单统计
     */
    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> orderCountVos = baseMapper.selectOrderCount(orderCountQueryVo);
        List<Integer> countList = orderCountVos.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        List<String> dateList = orderCountVos.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        Map<String, Object> map = new HashMap(){{
           put("dateList",dateList) ;
           put("countList",countList);
        }};
        return map;
    }

    //设置orderInfo的状态码
    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }
}
